package demo.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import demo.dao.GenericDao;


public class GenericDaoImpl<T, ID extends Serializable> extends HibernateDaoSupport implements GenericDao<T, ID> {

	protected Class<T> entityClass;
//	private Logger logger = Logger.getLogger(getClass());
	
	@SuppressWarnings("unchecked")
	public GenericDaoImpl() {
//		logger.warn("----------------------------construtor...");
		this.entityClass = (Class) ((ParameterizedType)(getClass().getGenericSuperclass())).getActualTypeArguments()[0];
	}	
	
	@SuppressWarnings("unchecked")
	@Override
	public ID save(T t) {
		return (ID) getHibernateTemplate().save(t);
//		getHibernateTemplate().
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> queryAll() {
		String queryString = "from " + entityClass.getName();
		return getHibernateTemplate().find(queryString);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> queryByNameParam(String queryString, String[] paramNames, Object[] values) {
		return getHibernateTemplate().findByNamedParam(queryString, paramNames, values);
	}

	@Override
	public T queryById(ID id) {
		return getHibernateTemplate().get(entityClass, id);
	}

	@Override
	public void delete(ID id) {
		T t = getHibernateTemplate().get(entityClass, id);
		getHibernateTemplate().delete(t);
	}
	
	@Override
	public void delete(T t) {
		getHibernateTemplate().delete(t);
	}

	@Override
	public void update(T t) {
		getHibernateTemplate().update(t);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> queryByHql(String queryString) {
		return getHibernateTemplate().find(queryString);
	}

}
